<script lang="ts" setup>
import {
  addBook,
  deleteBook,
  editBook,
  getAuthor,
  getBooks,
  getPublish
} from "@/api/book";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, reactive, onMounted, getCurrentInstance } from "vue";

defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "Book"
});

onMounted(() => {
  onSearch();
});

const { proxy } = getCurrentInstance();
const loading = ref(true);
const tableData = ref([]);

const pagerConfig = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
  keyword: ""
});

const columns = reactive([
  {
    prop: "title",
    label: "书名"
  },
  {
    prop: "img_url",
    label: "书籍封面",
    type: "image"
  },
  {
    prop: "authors",
    label: "作者"
  },
  {
    prop: "price",
    label: "价格"
  },
  {
    prop: "publish",
    label: "出版社"
  }
]);

async function onSearch() {
  loading.value = true;
  let result = await getBooks(pagerConfig);
  pagerConfig.total = result.total;
  tableData.value = result.data.map(item => {
    item.title = "<< " + item.title + " >>";
    item.publish = item.publish.name;
    item.authors = item.authors.map(author => author.name).join(" ");
    return item;
  });
  // console.log(tableData.value);
}

const handleSearch = () => {
  pagerConfig.pageSize = 10;
  onSearch();
};

const handlePageChange = page => {
  pagerConfig.currentPage = page;
  onSearch();
};

// 添加的 form 数据
const form = reactive({
  id: "",
  title: "",
  img_url: "",
  price: "",
  authors_id: "",
  publish_id: ""
});

const formRef = ref();

const formLabelWidth = "80px";

// 图片封面
const imageUrl = ref("");

// 控制模拟态框的显示隐藏
const dialogVisible = ref(false);
// 区分编辑和新增
const action = ref("add");
const addClick = () => {
  dialogVisible.value = true;
  loading.value = false;
  getData();
  action.value = "add";
};

const editClick = row => {
  dialogVisible.value = true;
  loading.value = false;
  getData();
  action.value = "edit";
  form.id = row.id;
};

const deleteClick = row => {
  ElMessageBox.confirm("确定要删除吗?")
    .then(async () => {
      await deleteBook(row.id);
      ElMessage({
        showClose: true,
        message: "删除图书成功",
        type: "success"
      });
      onSearch();
    })
    .catch(() => {
      // catch error
    });
};

async function onSubmit() {
  (proxy.$refs.formRef as any).validate(async valid => {
    if (valid) {
      if (action.value == "add") {
        await addBook(form);
        ElMessage.success("新增图书成功~");
        onSearch();
        dialogVisible.value = false;
      } else if (action.value == "edit") {
        await editBook(form);
        ElMessage.success("修改图书成功~");
        onSearch();
        dialogVisible.value = false;
      }
      formRef.value.resetFields();
    } else {
      ElMessage({
        showClose: true,
        message: "表单格式错误！",
        type: "error"
      });
    }
  });
}

const cancelForm = () => {
  dialogVisible.value = false;
  formRef.value.resetFields();
};

const onClick = () => {
  onSubmit();
};

// 作者
const authorData = ref([]);
// 出版社
const publishData = ref([]);
async function getData() {
  let result = await getAuthor();
  authorData.value = result.data;
  result = await getPublish();
  publishData.value = result.data;
}

const rules = reactive<any>({
  title: [{ required: true, message: "必选项" }],
  price: [
    { required: true, message: "必选项" },
    { type: "number", message: "价格必须是数字" }
  ],
  authors_id: [{ required: true, message: "必选项" }],
  publish_id: [{ required: true, message: "必选项" }]
});

// 上传照片文件之前的钩子
const beforeAvatarUpload = rawFile => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("图书封面必须是 JPG 格式!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图书封面大小不能超过2MB!");
    return false;
  }
  return true;
};
const handleSuccess = (response, uploadFile) => {
  form.img_url = response.data.file;
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
};
</script>

<template>
  <div class="book">
    <div class="header">
      <el-button type="primary" @click="addClick">+新增</el-button>
      <el-form :inline="true">
        <el-form-item label="请输入">
          <el-input
            v-model="pagerConfig.keyword"
            placeholder="请输入书名"
            style="width: 400px"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table">
      <el-table :data="tableData">
        <el-table-column
          v-for="item in columns"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
        >
          <template v-if="item.type == 'image'" #default="scope">
            <el-image
              :src="'http://127.0.0.1:8000/upimg/' + scope.row.img_url"
              style="height: 50px; width: 50px"
            />
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" size="small" @click="editClick(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="deleteClick(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        small
        background
        layout="total, prev, pager, next"
        :total="pagerConfig.total"
        class="pager mt-4"
        @current-change="handlePageChange"
      />
    </div>

    <el-drawer
      v-model="dialogVisible"
      :title="action === 'add' ? '新增图书' : '编辑图书'"
      class="demo-drawer"
      :close="cancelForm"
    >
      <div class="demo-drawer__content">
        <el-form :model="form" ref="formRef" :rules="rules">
          <el-form-item label="书名" prop="title" :label-width="formLabelWidth">
            <el-input v-model="form.title" autocomplete="off" />
          </el-form-item>

          <el-form-item
            label="图书封面"
            prop="img_url"
            :label-width="formLabelWidth"
          >
            <el-upload
              class="avatar-uploader"
              action="http://127.0.0.1:8000/img_upload"
              :data="{ data: form.id }"
              :on-success="handleSuccess"
              :limit="1"
              :before-upload="beforeAvatarUpload"
              :show-file-list="false"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <IconifyIconOnline
                v-else
                class="avatar-uploader-icon"
                icon="ant-design:picture-outlined"
              />
            </el-upload>
          </el-form-item>

          <el-form-item label="价格" prop="price" :label-width="formLabelWidth">
            <el-input v-model.number="form.price" autocomplete="off" />
          </el-form-item>

          <el-form-item
            label="作者"
            prop="authors_id"
            :label-width="formLabelWidth"
          >
            <el-select v-model="form.authors_id" multiple placeholder="请选择">
              <el-option
                v-for="item in authorData"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="出版社"
            prop="publish_id"
            :label-width="formLabelWidth"
          >
            <el-select v-model="form.publish_id" clearable placeholder="请选择">
              <el-option
                v-for="item in publishData"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm">取消</el-button>
          <el-button type="primary" :loading="loading" @click="onClick">
            {{ loading ? "提交中 ..." : "提交" }}
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<style scoped>
.book {
  display: flex;
  justify-content: center;
  flex-direction: column;
  padding: 50px;
}

.header {
  display: flex;
  justify-content: space-between;
}

.table {
  margin-top: 20px;
  height: 620px;
}

.pager {
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
